<template>
  <div class="app-container">
    <el-form  :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库房名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入库房名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="库房类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择库房类型" clearable>
          <el-option v-for="dict in dict.type.sysk_score_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['store:house:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['store:house:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="logicDelete"
          v-hasPermi="['store:house:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['store:house:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="库房名称" align="center" prop="name" />
      <el-table-column label="库房类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sysk_score_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="库房容量" align="center" prop="capacity" />
      <el-table-column label="实际库房占用量" align="center" prop="actualCapacity" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.actualCapacity < scope.row.capacity">未满</span>
          <span v-if="scope.row.actualCapacity == scope.row.capacity">已满</span>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="selectHouse(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['store:house:edit']">修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:house:remove']"
          >删除</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="logicDelete(scope.row)"
            v-hasPermi="['store:house:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或修改库房对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form :disabled="disable"
      ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库房名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入库房名称" />
        </el-form-item>

        <el-form-item label="库房地址" prop="location" id="mapForm" v-model="form.location">
          <div id="container" style="width: 260px;height: 260px;"></div>

        </el-form-item>


        <el-form-item label="库房类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择库房类型">
            <el-option v-for="dict in dict.type.sysk_score_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库房容量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入库房容量" />
        </el-form-item>
        <el-form-item label="实际库房占用量" prop="actualCapacity">
          <el-input v-model="form.actualCapacity" placeholder="请输入实际库房占用量" />
        </el-form-item>
        <el-form-item label="附件" prop="attach">
          <file-upload v-model="form.attach" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import { listHouse, getHouse, delHouse, addHouse, updateHouse, logicDelHouse } from "@/api/store/house";
let map = null;
import AMapLoader from '@amap/amap-jsapi-loader';
export default {

  name: "House",
  dicts: ['sysk_score_type'],
  mounted() {

  },
  unmounted() {
    this.map?.destroy();
  },
  data() {
    return {
      storedLocation: [120.121288,30.222724],
      address: null,
      disable : false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库房表格数据
      houseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        status: null,
      },
      // 表单参数
      form: { location: '' },
      // 表单校验
      rules: {
        name: [
            { required: true, message: '请输入库房名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择库房类型', trigger: 'change' }
          ],
          remark: [
            { required: true, message: '请添加一条备注说明用途', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          capacity: [
          {
            required: true,  message: '请输入一个整数',  trigger: 'blur'
          },
          {
            pattern: /^[+-]?\d+$/,message: '输入的值必须是一个整数',trigger: 'blur'
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },

  methods: {

    //地图初始化
    initAMap(tempLocation) {
      let _form = this.form;
      window._AMapSecurityConfig = {
        securityJsCode: "5f9a65ac6d1c856dd3507d4d89185bb5",
      };
      AMapLoader.reset()
      AMapLoader.load({
        key: "32d4388f3404c40fd139a6d3f2702f2c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: tempLocation, // 初始化地图中心点位置
          });

          var currentMarker = new AMap.Marker({
            position: tempLocation,
            map:map
          }); // 用于存储当前的标记

          // 监听地图点击事件
          map.on('click', function (e) {
            var lnglat = e.lnglat; // 获取点击点的经纬度
            var lng = lnglat.getLng(); // 经度
            var lat = lnglat.getLat(); // 纬度

            // 在页面上显示经纬度
            console.log('经度: ' + lng + ', 纬度: ' + lat);

            // this.form.location = lng + lat;
            _form.location = lng +','+ lat;

            console.log(_form)

            // 如果已经存在标记，先将其从地图上移除
            if (currentMarker) {
              currentMarker.setMap(null);
            }

            // 创建新标记
            currentMarker = new AMap.Marker({
              position: lnglat,
              map: map
            });

            // 可选：设置标记的自定义图标
            currentMarker.setIcon('https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png');
            // 可选：设置标记的弹出信息
            var infoWindow = new AMap.InfoWindow({
              content: '<div>经度: ' + lng + '<br>纬度: ' + lat + '</div>',
              offset: new AMap.Pixel(0, -30)
            });
            currentMarker.on('click', function () {
              infoWindow.open(map, currentMarker.getPosition());
            });
          });
        }).catch((e) => {
          console.log(e);
        });
    },
    anotherinitAMap(tempLocation) {
      let _form = this.form;
      window._AMapSecurityConfig = {
        securityJsCode: "5f9a65ac6d1c856dd3507d4d89185bb5",
      };
      AMapLoader.reset()
      AMapLoader.load({
        key: "32d4388f3404c40fd139a6d3f2702f2c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: tempLocation, // 初始化地图中心点位置
          });

          var currentMarker = new AMap.Marker({
            position: tempLocation,
            map:map
          }); // 用于存储当前的标记

         ;
        }).catch((e) => {
          console.log(e);
        });
    },


    // 查看按钮
    selectHouse(row) {
      const id = row.id || this.ids
      getHouse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看库房";
        const tempStrArr = this.form.location.split(',');
        const numArray=tempStrArr.map(str => parseFloat(str));
        this.anotherinitAMap(numArray);
      });

      this.disable=true;
    },
    /** 查询库房列表 */
    getList() {
      this.loading = true;
      listHouse(this.queryParams).then(response => {
        this.houseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        location: null,
        type: null,
        capacity: null,
        actualCapacity: null,
        attach: null,
        remark: null,
        status: null,
        createUser: null,
        createTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.disable=false;
      this.reset();
      this.open = true;
      this.title = "添加库房";
      this.initAMap(this.storedLocation);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disable=false;
      const id = row.id || this.ids
      getHouse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库房";
        const tempStrArr = this.form.location.split(',');
        const numArray=tempStrArr.map(str => parseFloat(str));
        this.initAMap(numArray);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();

            });
          }
        }
      });
    },
    // /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否确认删除库房编号为"' + ids + '"的数据项？').then(function() {
    //     return delHouse(ids);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {});
    // },
    /** 逻辑删除按钮操作 */
    logicDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库房编号为"' + ids + '"的数据项？').then(function () {
        return logicDelHouse(ids);
      }).then(() => {

        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('store/house/export', {
        ...this.queryParams
      }, `house_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
